package com.bio.service.attachment.impl;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.commons.lang.StringUtils;
import com.bio.dao.attachment.AttachmentDAO;
import com.bio.entity.attachemnt.Attachment;
import com.bio.service.attachment.AttachmentService;
import com.bio.service.impl.AbstractService;

public class AttachmentServiceImpl extends AbstractService<Attachment, AttachmentDAO> implements AttachmentService{

	public AttachmentServiceImpl(AttachmentDAO dao) {
		super(dao);
	}

	@Override
	public String batchProcess(List<Attachment> attachments, String existedPicInfos, List<String> deletedPics){
		JSONArray jArray = new JSONArray();
		if(StringUtils.isNotEmpty(existedPicInfos)){
			jArray = JSONArray.fromObject(existedPicInfos);
		}
		
		//把要删除的附件删除
		Iterator<JSONObject> jObjects = jArray.iterator();
		if(null != deletedPics){
			for(String id : deletedPics){
				dao.remove(Long.valueOf(id));
			}
			while(jObjects.hasNext()){
				JSONObject object = jObjects.next();
				if(deletedPics.contains(object.getString("attId"))){
					jObjects.remove();
				}
			}
		}
		
		if(null == attachments){
			return jArray.toString();
		}
		
		for(Attachment attachment : attachments){
			File file = attachment.getFile();
			try {
				FileInputStream fileInputStream = new FileInputStream(file);
				int fileSize = fileInputStream.available();
				byte datas[] = new byte[fileSize];
				while(fileInputStream.read(datas)!=-1){
					fileInputStream.read(datas);
				}
				attachment.setSize(fileSize);
				attachment.setData(datas);
				attachment = dao.save(attachment);
				JSONObject jObject = new JSONObject();
				jObject.accumulate("attName", attachment.getFileFileName());
				jObject.accumulate("attId", attachment.getId());
				jArray.put(jObject);
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return jArray.toString();
	}
}
